package dao

import (
	"behavior_srv/handler/models"
	"gorm.io/gorm"
)

// VisitRecordDAO 访问记录DAO
type VisitRecordDAO struct {
	DB *gorm.DB
}

// Create 创建单条访问记录
func (dao *VisitRecordDAO) Create(visit *models.BehaviorVisitRecords) error {
	return dao.DB.Create(visit).Error
}

// BatchCreate 批量创建访问记录
func (dao *VisitRecordDAO) BatchCreate(visits []*models.BehaviorVisitRecords) error {
	return dao.DB.CreateInBatches(visits, 100).Error
}

// GetByUserID 获取指定用户的访问记录
func (dao *VisitRecordDAO) GetByUserID(userID int64, limit, offset int) ([]*models.BehaviorVisitRecords, error) {
	var visits []*models.BehaviorVisitRecords
	query := dao.DB.Where("user_id = ?", userID).Order("created_at DESC")
	if limit > 0 {
		query = query.Limit(limit).Offset(offset)
	}
	err := query.Find(&visits).Error
	return visits, err
}

// CountByUserID 统计指定用户的访问记录数量
func (dao *VisitRecordDAO) CountByUserID(userID int64) (int64, error) {
	var count int64
	err := dao.DB.Model(&models.BehaviorVisitRecords{}).Where("user_id = ?", userID).Count(&count).Error
	return count, err
}

// GetByPath 获取指定路径的访问记录
func (dao *VisitRecordDAO) GetByPath(path string, limit, offset int) ([]*models.BehaviorVisitRecords, error) {
	var visits []*models.BehaviorVisitRecords
	query := dao.DB.Where("path = ?", path).Order("created_at DESC")
	if limit > 0 {
		query = query.Limit(limit).Offset(offset)
	}
	err := query.Find(&visits).Error
	return visits, err
}

// CountByPath 统计指定路径的访问记录数量
func (dao *VisitRecordDAO) CountByPath(path string) (int64, error) {
	var count int64
	err := dao.DB.Model(&models.BehaviorVisitRecords{}).Where("path = ?", path).Count(&count).Error
	return count, err
}
